<?php
if ( file_exists("config.php") ) {
	include_once "config.php";
}

	if ( ! isset( $_SESSION ) ) {
		session_start();
	}
	
	function open_connection_pdo() {
		try {
		  $db = new PDO ( sprintf('mysql:host=%s;port=%s;dbname=%s', 
		  DBHOST, DBPORT, DBNAME), USER, PASSWORD );		
		} catch (PDOException $e) {
		  die("Failed to connect to database!<br> You should check 
		  DB connection, and the config.php file at the app installation location.");		
		}
	return $db;
	}

	function logged_in() {	
		# if not logged in, then we set logged_in_as to -1
		return ( ( logged_in_as() == -1 ) ? false : true );
	}
	
	function logged_in_as() {
		// If the user has logged in, then SESSION will have the user_id.
		// return that.
		// otherwise, return -l
		
		return ( isset ( $_SESSION['user_id'] ) ? $_SESSION['user_id']: -1 );
	}
	
	function is_author( $note_id ) {
		$pdo = open_connection_pdo();
		
		$stmnt = $pdo->prepare( sprintf("SELECT note_author FROM NOTES WHERE 
		note_id='%s'", $note_id ) );
		$stmnt->execute();
		$result = $stmnt->fetch( PDO::FETCH_ASSOC );
		$note_author = $result["note_author"];
		
		$pdo = null;
// If the logged in user is really the owner of the note, then. allow him to edit.
		if ( $note_author == logged_in_as() ) {
			return true;
		} else {
			return false;
		}
		
	}
	
	function get_note_author( $note_id ) {
		$pdo = open_connection_pdo();
		$stmnt = $pdo->prepare( sprintf("SELECT note_author FROM NOTES WHERE 
		note_id='%s'", $note_id ) );
		$stmnt->execute();
		$result = $stmnt->fetch( PDO::FETCH_ASSOC );
		$note_author = $result["note_author"];
		
		$pdo = null;
		
		return $note_author;
	}	
	
	function get_note_author_name ( $note_id ) {
		$note_author = get_note_author( $note_id );
		$pdo = open_connection_pdo();
		$stmnt = $pdo->prepare( "SELECT user_name FROM users WHERE user_id = :note_author" );
		$stmnt->bindParam(":note_author", $note_author);
		$stmnt->execute();
		$note_author_name = $stmnt->fetch( PDO::FETCH_ASSOC );
		$note_autor_name = $note_author_name["user_name"];
		
		$pdo = null;
		
		return $note_autor_name;
	}
	
	function access_protocol() {
		$protocol = ( ! empty($_SERVER['HTTPS'] ) ) ? "https://" : "http://";
		return $protocol;
	}
	
	function this_page_url() {
		$protocol = access_protocol();
		$this_page_url = sprintf("%s%s%s", 
						access_protocol(),
						$_SERVER['SERVER_NAME'], 
						$_SERVER['PHP_SELF']
					);
		return $this_page_url;
	}
	
	function get_header( $page_title, $header_title ) {
	?>
	<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html>
	<head>
		<link href="css/notesrack.css" rel="stylesheet" type="text/css">
		<script type="text/javascript" src="js/jquery.min.js"></script>
		
		<script src="js/tinymce.min.js"></script>
		<!-- Place inside the <head> of your HTML -->
		<script type="text/javascript">
		tinymce.init({
			selector: "textarea.note_content",
			mode:	"exact",
			menubar:  false
		 });
		</script>	
	</head>
	<body>
	<div id="box">			
			<div id="header">
				<title><?php echo $page_title;?> </title>
				<a id="tool_title" href="<?php echo get_url_to("notes.php");?>" title="Retrieves all public notes from everyone + your notes."> Notes </a>
					<div id="filter_notes">			
					<?php if ( logged_in() ) { ?>			
						<span>My notes: </span>
						<a id="my_notes" href="<?php echo get_url_to("notes.php");?>?my_notes">All</a>
						<a id="my_private_notes" href="<?php echo get_url_to("notes.php");?>?my_private_notes">Private</a>
						<a id="my_public_notes" href="<?php echo get_url_to("notes.php");?>?my_public_notes">Public</a>
						<a id="logout" href="<?php echo get_url_to("user.php?logout");?>" title="Logged in as <?php echo $_SESSION['username'];?>">
						Logout</a>
						<?php echo create_note();?>
					<div id="create_note_popup"></div>					
					<?php } else { # If not logged in 
						create_note(); # This displays create note link if logged in. otherwise, login link.
					}
					echo "</div>";					
			get_search_box();
			printf( '<h4 id="header_title">%s</h4>', $header_title );
			echo '<div id="notify"></div>';				
			echo '</div>'; // Close of id="header"
			
			
	} # Close of get_header()
	
	function get_footer() {
		echo '</div><!--close of id="box" -->
		<script type="text/javascript" src="js/notes.js"></script>
	</body>
</html>';
	exit;
	}
	
	
	function get_note_details( $note_id, $purpose ) {
		$response = array( "note_details"		=>	"",
							"fail"				=>	"",
							"failure_message"	=>	"",
							"pass"				=>	""
						);
		
		if ( is_author( $note_id ) ) {
			$pdo = open_connection_pdo();
				$stmnt = $pdo->prepare( sprintf("SELECT * FROM NOTES WHERE note_id='%s'", $note_id ) );
				$stmnt->execute();
				$note_details = $stmnt->fetch( PDO::FETCH_ASSOC );
				if ( count( $note_details ) == 0 ) {
					$response["fail"]			= "fail";
					$response["failure_message"]	= "No notes found for the given criterian! Reload the page, and try editing.";				
				} else {
					$response["note_details"] = 	$note_details;
					$response["pass"]		  = 	"pass";
				}
			
			$pdo = null;
			return $response;
		}
	}
	
	function run_query ( $query ) {
		/* Returns an array of results based on the query passed. */
		try { 
			$pdo = open_connection_pdo();
			$stmnt = $pdo->prepare( $query );
			$stmnt->execute();
			$results = $stmnt->fetchAll();
		} catch( PDOException $e ) {
			echo sprintf("Internal Error: Could not fetch results: %s", $e->getMessage() );
			$pdo = null;
			die();
		}
		$pdo = null;
		return $results;
	}
	
	function get_notes( $notes_type ) {
		
		$logged_in_as = logged_in_as();
		try {
			$pdo = open_connection_pdo();
		
			if ( $notes_type == "all_notes" )  {
				$stmnt = $pdo->prepare( sprintf("SELECT note_id, note_title, note_content, note_tags FROM NOTES WHERE note_author='%s' OR note_privacy='%s'", logged_in_as(), "public") );
			}
			
			if ( $notes_type == "my_notes" )  {
				$stmnt = $pdo->prepare("SELECT * FROM notes WHERE note_author=:note_author");				
				$stmnt->bindParam(":note_author", $logged_in_as );				
			}
			
			if ( $notes_type == "my_private_notes" )  {
				$stmnt = $pdo->prepare("SELECT * FROM notes WHERE note_author=:note_author AND note_privacy='private' ");
				$stmnt->bindParam(":note_author", $logged_in_as );
			}
			
			if ( $notes_type == "my_public_notes" )  {
				$stmnt = $pdo->prepare("SELECT * FROM notes WHERE note_author=:note_author AND note_privacy='public' ");
				$stmnt->bindParam(":note_author", $logged_in_as );
			}
			
			
			$stmnt->execute();
			
			$results = $stmnt->fetchAll();			
			} catch( PDOException $e ) {
				array_push( $errors, sprintf("Internal Error: Could not save the note to database: %s", $e->getMessage() ) );
			}

		$pdo = null;
		return $results;
	}
	
	
	
	function htmlize_single_note( $note_dettails ) {
		if ( count( $note_dettails ) == 0 ) {
			echo '<div id="rack">
				<div id="noresults">This is quite unexpected! No results found for this note.</div>
			</div>';
		}	
		?>
			<div id="rack">
			</div>
		<?php
		
			return;
		
		
	}
	
	
	function htmlize_notes ( $results, $to_display_on ) {
		
		if ( count( $results ) == 0 ) {
			echo '<div id="rack">
				<div id="noresults">No notes to display.</div>
			</div>';
			
			return;
		}
	?>
	
		<div id="rack">
			<?php
				/* Using to_display_on, we decide how the tags href, or any other 
				 * href should adjust itself.
				 * For instance, the href to a tag on "my_private_notes" should
				 * fetch only the private notes tags tagged with given tag.
				 
				 * and to achieve this, the href to the tag will have additional 
				 * GET param along with the tag name and it says fetch only private notes 
				 */ 
				$palette = "bright";				
				for( $i = count($results) - 1; $i >= 0; $i-- ) {
					// Alternate the class name so that the notes appear distinct.
					( $palette = ( $palette == "bright" ) ? "dim" : "bright" );
					$note_id = $results[$i]["note_id"];						
					$edit_link = "";
					$delete_link = "";
					$view_note_url = get_url_to( sprintf( "notes.php?view_note&note_id=%s", $note_id ) );
					
					if ( is_author ( $note_id ) ) {
						$edit_link = sprintf( '<span> <a class="edit_note" id="note-%s" href="%s?edit&note_id=%s">Edit</a></span>', $note_id, this_page_url(), $note_id );
						$delete_link = sprintf( '<span> <a class="delete_note" id="note-%s" href="%s?delete&note_id=%s">Delete</a></span>', $note_id, this_page_url(), $note_id );
					}
					
					$comments = sprintf('<span><a class="get_comments" id="note-%s" href="%s?comments&note_id=%s" title="Did you find something wrong in this note? You can let the note author know by clicking here.."> Comments?</a></span>',
					             $note_id, get_url_to("notes.php"), $note_id );
								 
					$note_content = $results[$i]["note_content"];
											
					echo sprintf('<div id="note-%s" class="note %s">', $note_id, $palette );
					echo sprintf('<div class="note_title"><a href="%s" class="note_link">%s</a>%s %s %s</div>', $view_note_url, $results[$i]["note_title"], $edit_link, $delete_link, $comments );
					echo sprintf('<div class="note_content">%s</div>', $results[$i]["note_content"] );
					$tags = ( strlen($results[$i]["note_tags"]) > 0 ? explode ( ",", $results[$i]["note_tags"] ) :"" );
					echo '<div class="note_footer">';
					echo '<div class="note_tags">Tagged with: ';
					if ( gettype($tags) == "array" ) { # then there are more than 1 tags.
						if ( count($tags) > 0 ) {							
								for ( $tag_count = 0; $tag_count < count($tags); $tag_count++ ) {
									echo sprintf('<span class="tags"><a href="%s?%s&tag=%s">%s</a></span> ',
											this_page_url(), 
											$to_display_on, 
											trim($tags[$tag_count]), 
											trim($tags[$tag_count])
										);
								}
						} else { # ok. only one tag.
							echo sprintf('<span class="tags"><a class="tag_href" href="%s?tag=%s">%s</a></span> ',
								this_page_url(), 
								$to_display_on, 
								trim( $tags ), 
								trim( $tags )
							);
						}
					} else { # no tags at all.
						echo '<span class="tags">No tags</span>';
					}							
					echo "</div>"; # Close of class="note_tags"
					echo '<div class="note_author">';
					echo sprintf( 'Author: <a class="get_notes_by_author" href="%s?author=%s">%s</a>', get_url_to("notes.php"), get_note_author_name($note_id), get_note_author_name( $note_id ) );
					echo '</div>';
					echo '</div>'; # Close of class="note_footer"
					echo "</div>"; # Close of id="note-%s"
				}
		?>
			<div id="comments_writeup"></div>
<?php
	}
	
	function get_notes_by_tag( $tag, $filter_criterion ) {
			$logged_in_as = logged_in_as();
			$tag = $tag;
			
			try {
				$pdo = open_connection_pdo();
				
				if ( $filter_criterion == "all_notes" )  {
					$stmnt = $pdo->prepare( sprintf("SELECT * FROM NOTES WHERE (note_author='%s' OR note_privacy='%s') AND note_tags LIKE :tag ", logged_in_as(), "public", $tag ) );
					
					$tag = "%" . $tag . "%";
					$stmnt->bindParam(":tag", $tag);
				}
				
				if ( $filter_criterion == "my_notes" )  {
					$stmnt = $pdo->prepare( sprintf( "SELECT * FROM notes WHERE note_author=:note_author AND note_tags LIKE :tag" ) );	
					
					$stmnt->bindParam(":note_author", $logged_in_as );
					$tag = "%" . $tag . "%";
					$stmnt->bindParam(":tag", $tag);					
				}
				
				if ( $filter_criterion == "my_private_notes" )  {
					$stmnt = $pdo->prepare( "SELECT * FROM notes WHERE ( note_author=:note_author AND note_privacy='private' ) AND note_tags LIKE :tag" );
					$stmnt->bindParam(":note_author", $logged_in_as );
					$tag = "%" . $tag . "%";
					$stmnt->bindParam(":tag", $tag);					
				}
				
				if ( $filter_criterion == "my_public_notes" )  {
					$stmnt = $pdo->prepare("SELECT * FROM notes WHERE note_author=:note_author AND note_privacy='public' AND note_tags LIKE :tag" );
					
					$stmnt->bindParam(":note_author", $logged_in_as );
					$tag = "%" . $tag . "%";
					$stmnt->bindParam( ":tag", $tag );					
				}			
				$stmnt->execute();
				
				$results = $stmnt->fetchAll();
				} catch( PDOException $e ) {
					array_push( $errors, sprintf("Internal Error: Could not save the note to database: %s", $e->getMessage() ) );
				}
			return $results;
			
	}
	
	function get_notes_by_id( $note_id ) {	
		$pdo = open_connection_pdo();
		
		try {
			$stmnt = $pdo->prepare("SELECT * FROM notes WHERE note_id=:note_id" );					
			$stmnt->bindParam(":note_id", $note_id );
			$stmnt->execute();		
			$results = $stmnt->fetch(PDO::FETCH_ASSOC);
		} catch( PDOException $e ) {
			array_push( $errors, sprintf("Internal Error: Could not save the note to database: %s", $e->getMessage() ) );
		}
		return $results;				
	}
	
	
	function get_url_to( $page ) {
		$url = dirname(this_page_url()) . "/" . $page;
		return $url;
	}


	function create_note_form() {
	?>
	<div id="modal_create_note">		
			<form action="#" method="POST" id="write_note">
				<div class="note_title_wrap">
					<div class="sub_heading"> Note title: </div>
					<input value="" required="required" type="text" name="note_title" id="note_title" autocomplete="off" maxlength="256" size="56" placeholder="Note title. Preferably a crispy one!">
					<!--
					<div id="write_note_suggestions">
						<div class="suggestion"><a class="suggested_note" href="google.com">How about this </a></div>
						<div class="suggestion"><a class="suggested_note" href="google.com">How about this </a></div>
						<div class="suggestion"><a class="suggested_note" href="google.com">How about this </a></div>
						<div class="suggestion"><a class="suggested_note" href="google.com">How about this </a></div>					
					</div>
					-->
				</div>
				
			
				<div class="sub_heading"> Note content: </div>
			
				<textarea class="note_content" name="content"></textarea>				
				<div class="sub_heading">Private note? Yes.<input type="checkbox" title="If checked, then this note will be visible ONLY to you. Othrewise, to everyone." name="note_privacy" id="note_privacy">
				</div>
				
				<div id="tags">
					<div class="sub_heading">Tags:(comma separated) </div>
					<input required="required" type="text" name="note_tags" id="note_tags" autocomplete="off" maxlength="256" size="56" placeholder="Tags for this note. Comma seperated." value="">
				</div>
				
				<input type="button" id="submit_note" value="Submit!">
				<a href="<?php echo get_url_to("notes.php")?>" class="button_mainpage">
					<input type="button" value="Close">
				</a>
			</form>
			<div id="write_note_outcome"></div>			
		</div>
		<div id="write_note_suggestions">
			<h3>Similar notes</h3>
			<div id="suggestions"></div>
		</div>
		
<?php	
	}
	
function create_note() {
	if ( logged_in() ) {
		echo sprintf('<a class="create_note" href="%s">Write Note</a>', get_url_to("write.php"));
		echo '<div id="create_note_popup"></div>';
	} else {
		echo sprintf('<a id="user_login" href="%s" title="Login to write a new note.">Login</a>', get_url_to("user.php"));
		echo '<div id="user_authentication"></div>';
		echo '<div id="user_registration"></div>';
		echo '<div id="user_passwordreset"></div>';
	}
}	


function check_login( $username, $password ) {
/* 
 * 
 */
	$response = array( 
						"errors" 	=>		"",
						"success"	=>		"",
				);
				
	$pdo = open_connection_pdo();
	$stmnt = $pdo->prepare( "SELECT passphrase FROM users WHERE user_name=:username" );
	$stmnt->bindParam( ":username", $username );
	$stmnt->execute();
	$result = $stmnt->fetch( PDO::FETCH_ASSOC );
	
	
	if ( $result["passphrase"] == "" ) {
		# i.e the username itself is not found!
		# ask the user if he is interested in registering this username..
		$response["errors"] .= sprintf( "Username %s doesn't exist. You can register this user for yourself if you want.", $username );
	} else {
		$given_password_hashed = crypt( $password, get_attribute( "passphrase_salt" ) );
		
		if ( $result["passphrase"] == $given_password_hashed ) {
			$response["success"] .= "success";
			$response["redirect_to"] = get_url_to("notes.php");
			
			# Also, put the user_id into session.
			$_SESSION['user_id'] = get_user_id( $username );
			$_SESSION['username'] = $username;
		} else {
			# Ok. Password is invalid.
			$response["errors"] .= "Login failed. Invalid username, or password.";
		}
	}
	
	return $response;
}

function duplicate_entry( $value, $table, $column ) {
/*  Accepts a value, a column name, and a table name,
 *  Returns true if the value exists. Else false.
 *
 */
	$pdo = open_connection_pdo();
	$stmnt = $pdo->prepare( sprintf("SELECT count(*) AS entries FROM %s WHERE %s=:value", $table, $column ) );
	$stmnt->bindParam( ":value", $value );
	$stmnt->execute();
	$result = $stmnt->fetch( PDO::FETCH_ASSOC );
	if ( $result["entries"] == 0 ) {
		$pdo = null;
		return false;
	} else {
		$pdo = null;
		return true;
	}  
}

function get_attribute( $attr_name ) {
/*
 *
 */ 
 	$pdo = open_connection_pdo();
	$stmnt = $pdo->prepare( sprintf("SELECT value FROM configuration WHERE param='%s'", $attr_name ) );
		
	$stmnt->execute();
	$result = $stmnt->fetch( PDO::FETCH_ASSOC );
	
	$pdo = null;
	
	if ( count($result) > 1 ) {
		return false;
	} else {
		return $result["value"];
	}
	
}

function register_user( $username, $password, $email ) {
	$response = array( 
						"errors" 			=>		"",
						"success"			=>		"",
						"registered_user"	=>		""
				);
	if ( duplicate_entry ( $username, "users", "user_name" ) ) {
		# i.e the username is already taken.
		$response["errors"] .= sprintf( "<div>Sorry, the username %s exists. Try another username.</div>", $username );
	}
	
	if ( duplicate_entry ( $email, "users", "user_email" ) ) {
		# i.e the username is already taken.
		$response["errors"] .= sprintf( "<div>Sorry, the email address %s is registered. You can reset password if you own this email account!</div>", $email );
	}
	
	if ( $response["errors"] != "" ) {
		# something went wrong.
		return $response;
	}

	try {
		$pdo = open_connection_pdo();
		$passphrase = crypt( $password, get_attribute("passphrase_salt") );
			
		$stmnt = $pdo->prepare("INSERT INTO USERS( user_name, user_email, passphrase ) VALUES(:username, :user_email, :passphrase) ");
		
		$stmnt->bindParam(":username", $username );
		$stmnt->bindParam(":user_email", $email );
		$stmnt->bindParam(":passphrase", $passphrase );
		
		$result = $stmnt->execute();
		
		$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
		$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); 
	} catch( PDOException $e ) {			
			$response["errors"] .= sprintf("<span>Sorry, but user registration failed. Please retry.</span>");
			$pdo = null;
			return $response;
	}
	
	$response["success"] .= sprintf("<span>Registration successful! Login using the credentails you just submitted.</span>");
	$response["registered_user"] .= $username;
	$pdo = null;
	return $response;
}


function json_return_debug_output( $message ) {
	return true;
	$debug = array( "debug:"	=>	$message);
	echo json_encode($debug);
}

function get_user_id( $username ) {
 	$pdo = open_connection_pdo();
	$stmnt = $pdo->prepare( "SELECT  user_id FROM users WHERE user_name=:username" );
	$stmnt->bindParam(":username", $username);
	
	$stmnt->execute();
	$result = $stmnt->fetch( PDO::FETCH_ASSOC );
	if ( count($result) > 1 ) {
		// This is an embarrassing situation.
		// how could there be more than one user_id for the same user_name!?
		$pdo = null;
		return false;
	}
	$pdo = null;
	return $result["user_id"];
}


function get_user_name( $user_id ) {
 	$pdo = open_connection_pdo();
	$stmnt = $pdo->prepare( "SELECT user_name FROM users WHERE user_id=:user_id" );
	$stmnt->bindParam(":user_id", $user_id);
	
	$stmnt->execute();
	$result = $stmnt->fetch( PDO::FETCH_ASSOC );
	if ( count($result) > 1 ) {
		// This is an embarrassing situation.
		// how could there be more than one user_id for the same user_name!?
		$pdo = null;
		return false;
	}
	$pdo = null;
	return $result["user_name"];
}

function get_login_form() {
?>	
	<div id="modal_login">
	<form action="<?php echo get_url_to("user.php?login");?>" method="POST" name="login_form" id="login_form">
		<h3 class="subtitle">Login to add a note</h3>
		<table>
			<tr>
				<td>Username:</td> 
				<td><input type="text" autocomplete="off"  placeholder="User name" name="username" required></td>
			</tr>
			<tr>
				<td>Password: </td> 
				<td><input type="password" placeholder="Password"name="password" required></td>
			</tr> 
			<tr>
				<td><input type="button" name="login" id="login" value="Login"></td>
				<td><input type="button" name="cancel" id="cancel_login" value="Cancel"></td>				
			</tr>
			<tr>
				<td>New user?</td>
				<td><a href="#" id="create_account">Create an account!</td>				
			</tr>
			<tr>
				<td>Forgot password?</td>
				<td><a href="#" id="get_reset_password_form">Reset your password</td>				
			</tr>
		</table>
	</form>
	<div id="login_outcome"></div>
	</div> <!-- close of modal_login -->
<?php 
}

function get_register_user_form() {
?>
	<div id="modal_register">
	<form action="<?php echo get_url_to("user.php?register");?>" method="POST" name="register_form" id="register_form">
		<h3 class="subtitle">Create an account</h3>
		<table>
			<tr>
				<td>Username:</td> 
				<td><input type="text" autocomplete="off"  placeholder="User name" name="username" required></td>
			</tr>
			<tr>
				<td>Email address:</td> 
				<td><input type="text" autocomplete="off"  placeholder="Email address" name="email" required></td>
			</tr>
			<tr>
				<td>Password: </td>
				<td><input type="password" placeholder="Password"name="password" required></td>
			</tr> 
			<tr>
				<td><input type="button" name="register_account" id="register_account" value="Register account"></td>
				<td><input type="button" name="cancel" id="cancel_register_user" value="Cancel"></td>				
			</tr>			
		</table>
	</form>
	<div id="registeration_outcome"></div>
	</div> <!-- close of modal_register -->

<?php
}



function get_passwordreset_form() {
?>
	<div id="modal_passwordreset">
	<form action="<?php echo get_url_to("user.php?password_reset");?>" method="POST" name="password_reset" id="passwordreset_form">
		<h3 class="subtitle">Reset password</h3>
		<table>
			<tr>
				<td>Username:</td> 
				<td><input type="text" autocomplete="off"  placeholder="User name" name="username" required></td>
			</tr>
			<tr>
				<td>Old password:</td> 
				<td><input type="password" placeholder="Old password" name="old_password" required></td>
			</tr>
			<tr>
				<td>New password: </td>
				<td><input type="password" placeholder="New password"name="new_password" required></td>
			</tr> 
			<tr>
				<td><input type="button" name="Reset Password" id="reset_password" value="Reset Password"></td>
				<td><input type="button" name="cancel" id="cancel_password_reset" value="Cancel"></td>			
			</tr>			
		</table>
	</form>
	<div id="passwordreset_outcome"></div>
	</div> <!-- close of modal_passwordreset -->

<?php
}



function get_search_box() {
?>
	<div id="search_box">
	<form action="<?php echo get_url_to("notes.php");?>" method="GET" name="search_form" id="search_form">
		<input type="text" autocomplete="off" id="q" width="55" placeholder="Search for notes" name="q" autocomplete="off" required>	
		<input type="submit" value="Search">
	</form>	
	</div> <!-- close of search_box -->
	
<?php
}

function search_notes( $query_string ) {
	$pdo = open_connection_pdo();
	
	/*  Explode the search text into words.
		Find the notes that contain each word.
		The note that contains all the words will be listed first.
		The note with lesser words will appear next, and so on...
	 */
	 
	$search_results = $notes = array();
	$search_text_exploded = preg_split( "/[\s]+/", $query_string );
	
	foreach ( $search_text_exploded as $st ) {
		try {
			$stmnt = $pdo->prepare( 'SELECT * FROM notes WHERE ( note_privacy="public" AND note_title like :search_text ) OR ( note_privacy="public"  AND note_content like :search_text )' ) ;
			
			$search_text = sprintf("%%%s%%", $st);
			$stmnt->bindParam( ':search_text', $search_text );
						
			$stmnt->execute();
			
			$results = $stmnt->fetchAll(PDO::FETCH_ASSOC);
			
			//var_dump($results);
			
			foreach ( $results as $result_item ) {
				if ( ! empty ( $result_item['note_id'] ) ) {
					$note_id = $result_item['note_id'];
					if ( isset( $search_results[$note_id] ) ) {
						$search_results[$note_id] += 1; // Increment it.
					} else {
						$search_results[$note_id] = 1; // Initalize it.
					}
				}
			}
		} catch( PDOException $e ) {
			echo sprintf("Internal Error: Could not fetch results: %s", $e->getMessage() );
			$pdo = null;
			die();
		}
	}
	
	arsort( $search_results ); // reverse search the array so that we get the notes more serch terms first,
							 // then those with less terms..
	
	$result_count = count( $search_results ) - 1;
	
	foreach ( $search_results as $matching_note => $howmany_search_words ) {
		if ( defined( 'NOTESRACK_DEBUG' ) ) {
			echo sprintf("<pre>note_id: %s note_title:%s Number of search words found: %s</pre>", $matching_note, get_note_title($matching_note), $howmany_search_words);
		}
		
		$notes[$result_count] = get_notes_by_id($matching_note);
		$result_count--;
	}
	
	$pdo = null;
	return $notes;
}

function get_notes_by_author ( $author ) {
	$pdo = open_connection_pdo();
	
	$stmnt = $pdo->prepare( "SELECT * FROM NOTES WHERE note_author=:note_author AND note_privacy='public' " );
	$author = get_user_id ( $author );
	$stmnt->bindParam( ":note_author", $author );
	$stmnt->execute();
	
	$notes = $stmnt->fetchAll();
	$pdo = null;
	return $notes;	
}

function delete_note ( $note_id ) {
	$response = array( 
						"errors" 	=>		"",
						"success"	=>		"",
				);

	if ( is_author( $note_id ) ) {
		try {
			$pdo = open_connection_pdo();
			$stmnt = $pdo->prepare( "DELETE FROM notes WHERE note_id=:note_id" );
			$stmnt->bindParam( ":note_id", $note_id );
			$stmnt->execute();
		} catch( PDOException $e ) {
			$response["errors"] .= "There was an internal error deleting this note. Please retry.";
			$pdo = null;
			return $reponse;
		}
	} else {
		$response["errors" ] .= "You cannot delete this note as you are not the owner.</div>";
		$pdo = null;
		return $response;
	}
	// i.e all good. the note has been deleted.
	$response["note_id"] = $note_id;
	$response["success"] = "Note has been deleted.";
	$pdo = null;
	return $response;
}

function password_reset( $username, $old_password, $new_password ) {
	$response = array ( 
						"errors" 			=>		"",
						"success"			=>		""						
				);
	
	$check_login = check_login( $username, $old_password );
	// If the given old password is correct, then, 
	// response will be an array with the index success set to success.
	
	if ( $check_login["success"] == "success" ) {
		// Ok, the given old password is right.
		// Go ahead and reset the password.		
		try {
			$pdo = open_connection_pdo();
			$passphrase = crypt( $new_password, get_attribute("passphrase_salt") );
				
			$stmnt = $pdo->prepare("UPDATE USERS SET passphrase = :passphrase WHERE user_name = :username");
			
			$stmnt->bindParam(":username", $username );
			$stmnt->bindParam(":passphrase", $passphrase );
			
			$result = $stmnt->execute();
			
			$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
			$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); 
		} catch( PDOException $e ) {			
				$response["errors"] .= sprintf("<span>Sorry, something went wrong resetting the password. Please retry.</span>");
				$pdo = null;
				return $response;
		}		
		$response["success"] .= sprintf("<span>Password has been reset. Login using the new password.</span>");
		$response["user_who_reset_password"] = $username;
		$pdo = null;
		return $response;
	} else {		
		if ( isset( $check_login["errors"] ) and ! empty( $check_login["errors"] ) ) {
			$response["errors"] .= $check_login["errors"];
		}
	}
	$pdo = null;
	return $response;	
}

function get_note_url($note_id) {
	return sprintf( get_url_to("notes.php?view_note&note_id=%s"), $note_id );
}

function get_note_title($note_id) {
	$pdo = open_connection_pdo();
	$stmnt = $pdo->prepare( sprintf("SELECT note_title FROM NOTES WHERE note_id='%s'", $note_id ) );
	$stmnt->execute();
	$note_details = $stmnt->fetch( PDO::FETCH_ASSOC );
	if ( count( $note_details ) == 0 ) {
		$note_title = "";
	} else {
		$note_title = $note_details['note_title'];
	}

	$pdo = null;
	return $note_title;
}

function get_suggestions ( $criterian, $query_string, $howmany_suggestions ) {
	
	if ( $criterian == "by_note_title" ) {
		
		$pdo = open_connection_pdo();

		/*  
			Explode the search text into words.
			Find the notes that contain each word.
			The note that contains all the words will be listed first.
			The note with lesser words will appear next, and so on...
		*/

		$suggestions = $notes = array();
		$search_text_exploded = preg_split( "/[\s]+/", $query_string );

		foreach ( $search_text_exploded as $st ) {
			try {
				$stmnt = $pdo->prepare( 'SELECT note_id FROM notes WHERE ( note_privacy="public" AND note_title like :search_text )' ) ;

				$search_text = sprintf("%%%s%%", $st);
				$stmnt->bindParam( ':search_text', $search_text );

				$stmnt->execute();

				$results = $stmnt->fetchAll(PDO::FETCH_ASSOC);
				
				foreach ( $results as $result_item ) {
					if ( ! empty ( $result_item['note_id'] ) ) {
						$note_id = $result_item['note_id'];
						if ( isset( $suggestions[$note_id] ) ) {
							$suggestions[$note_id] += 1; // Increment it.
						} else {
							$suggestions[$note_id] = 1; // Initalize it.
						}
					}
				}
			} catch( PDOException $e ) {
				echo sprintf("Internal Error: Could not fetch results: %s", $e->getMessage() );
				$pdo = null;
				die();
			}
		}
		
		$pdo = null;
		return $suggestions;
	}
}

function get_comments( $note_id ) {
	$pdo = open_connection_pdo();
	try {
		$stmnt = $pdo->prepare( 'SELECT * FROM comments WHERE note_id=:note_id' ) ;
		$stmnt->bindParam( ':note_id', $note_id );

		$stmnt->execute();
		
		$results = $stmnt->fetchAll(PDO::FETCH_ASSOC);		
	} catch( PDOException $e ) {
		echo sprintf("Internal Error: Could not fetch results: %s", $e->getMessage() );
		$pdo = null;
		die();
	}
	
	if ( count ($results) == 0 ) {
		echo '
		<table id="comments_table"></table>
		';
	} else {
		echo '<table id="comments_table">';
		for ( $i = 0; $i < count($results); $i++ ){ 
			echo sprintf('<tr><td class="comment_author">%s:</td><td class="comment_text">%s</td> <td class="comment_time"> %s</td></tr>', get_user_name($results[$i]['comment_author']), $results[$i]['comment_text'], $results[$i]['commented_at'] );
		}
		echo '</table>';
	}	
	return;
}

function get_comments_form( $note_id ) {
?>
	<h3>Your comments</h3>
	<form method="POST" id="comments_form">
		<input type="hidden" name="note_id" value="<?php echo $note_id;?>">
		<div><textarea name="comment_text" id="comment_textarea" placeholder="Comment ONLY if something is wrong in this note. Otherwise, please Do NOT write anything."></textarea></div>
		<input type="button" id="write_comments" value="Submit"/>
		<input type="button" id="cancel_write_comments" value="Cancel"/>
	</form>
	<div id="comment_submission_errors"></div>
<?php
	return;
}

?>





